package com.tencent.wxcloudrun.controller;

import com.tencent.wxcloudrun.config.ApiResponse;
import com.tencent.wxcloudrun.model.User;
import com.tencent.wxcloudrun.service.UserService;
import com.tencent.wxcloudrun.utils.UidUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author zhangshuai
 * @description
 * @create 2023/12/11 10:34
 */
@RestController
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 登录方法
     * @param user 用户信息
     * @return
     */
    @PostMapping(value = "/login")
    ApiResponse login(@RequestBody User user){
        String name = user.getName();
        String password = user.getPassword();
        //查询用户是否存在
        User dbUser = userService.getByName(name);
        if (dbUser!=null){
            //检查密码是否正确
            String dbPw = dbUser.getPassword();
            if (dbPw!=null&&dbPw!=""&&dbPw.equals(password)){
                return ApiResponse.ok(dbUser.getId());
            }
            return ApiResponse.error("用户存在，密码错误");
        }else {
            Integer uid = UidUtils.getUID();
            user.setId(uid);
            String errorMsg = userService.checkUserInfo(user);
            if (errorMsg!=null&&errorMsg!=""){
                return ApiResponse.error(errorMsg);
            }
            userService.saveUser(user);
            return ApiResponse.ok(uid);
        }
    }
}
